package com.example.qxfw.slhx.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.xt.SysConfig;
import com.example.qxfw.common.entity.yj.HxyjYzdisppara;
import com.example.qxfw.slhx.service.HxybService;
import com.example.qxfw.slhx.service.HxyjYzdispparaService;
import com.example.qxfw.ybzz.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "森林火险--火险预报")
@CrossOrigin
@RestController
@RequestMapping("/FireRiskForecastController")
public class FireRiskForecastController {

    @Value("${filePath.active}")
    private String active;

    @Autowired
    private HxybService hxybService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private HxyjYzdispparaService hxyjYzdispparaService;

    @ApiOperation("森林火险--火险因子--得到因子影响值")
    @PostMapping("/getInfluence")
    public SysResult getInfluence() {
        Map<String, Double> rltmap = new HashMap<>();
        List<SysConfig> sysConfigs = sysConfigService.getList("dq_hxpara");
        if (sysConfigs.size() > 0) {
            rltmap.put("森林因子", Double.parseDouble(sysConfigs.get(0).getParamvalue()));
        } else {
            rltmap.put("森林因子", 0.0);
        }
        List<SysConfig> sysConfigs2 = sysConfigService.getList("dq_hxqxpara");
        if (sysConfigs2.size() > 0) {
            rltmap.put("气象因子", Double.parseDouble(sysConfigs2.get(0).getParamvalue()));
        } else {
            rltmap.put("气象因子", 0.0);
        }
        return SysResult.success(rltmap);
    }

    @ApiOperation("森林火险--火险因子--保存因子影响值")
    @PostMapping("/saveInfluence")
    public SysResult saveInfluence(Double dzyz, Double skyl) {
        SysConfig config = new SysConfig();
        config.setParamname("dq_hxpara");
        config.setParamvalue(String.valueOf(dzyz));
        int i = sysConfigService.updateByParamName(config);

        config = new SysConfig();
        config.setParamname("dq_hxqxpara");
        config.setParamvalue(String.valueOf(skyl));
        i += sysConfigService.updateByParamName(config);
        return SysResult.success(i);
    }

    @ApiOperation("森林火险--火险因子--得到参数列表")
    @PostMapping("/getParameter")
    public SysResult getParameter() {
        List<HxyjYzdisppara> list = hxyjYzdispparaService.listByIndex(1);
        return SysResult.success(list);
    }

    @ApiOperation("森林火险--火险因子--修改参数")
    @PostMapping("/updateParameter")
    public SysResult updateParameter(HxyjYzdisppara para) {
        if (para.getId()==null||para.getId().equals("")){
            HxyjYzdisppara paraUp = hxyjYzdispparaService.save(para);
            return SysResult.success(paraUp);
        }
        HxyjYzdisppara paraUp = hxyjYzdispparaService.updateById(para);
        return SysResult.success(paraUp);
    }

    @ApiOperation("森林火险--火险因子--删除参数")
    @PostMapping("/deleteParameter")
    public SysResult deleteParameter(Integer id) {
        Integer rlt = hxyjYzdispparaService.deleteById(id);
        return SysResult.success(rlt);
    }

    @ApiOperation("森林火险--火险预报-自动分析")
    @PostMapping("/insertOfHxybWaring")
    public SysResult insertOfHxybWaring(String pos, int state) {
        int i = hxybService.insertOfHxybWaring(pos, state);
        return SysResult.success(i);
    }

    @ApiOperation("获取产品模板")
    @GetMapping("/getTemplate")
    public Object getTemplate() {
        //模板路径
        String templatePath;

        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        if (active.equals("dev")) {
            templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                    "\\src\\main\\resources\\Documents\\森林火险预报模板\\预警文档输出.docx";
        } else {
            templatePath = applicationHome.getSource().getParentFile() +
                    "\\resource\\Documents\\森林火险预报模板\\预警文档输出.docx";
        }
        // 设置前端响应
        byte[] buffer = new byte[1024];
        int bytesRead;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                FileInputStream inputStream = new FileInputStream(templatePath);
        ) {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", "森林火险预警文档模板.docx");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("模板下载失败");
        }
        return null;
    }

    @ApiOperation("获取产品最新期数")
    @GetMapping("getMaxId")
    public SysResult getMaxId() {
        Integer maxId = hxybService.getMaxId();
        return SysResult.success(maxId);
    }

    @ApiOperation("森林火险--火险预报--生成产品")
    @PostMapping("/createProduct")
    public Object creatProduct(Integer issueNum,
                               String userName,
                               String yjType,
                               String sXType,
                               String date,
                               Integer nTimes,
                               String colorAndPos,
                               String posStr,
                               MultipartFile[] images,
                               String layerName,
                               String dlData) {
        try {
            return hxybService.creatProduct(issueNum, userName, yjType, sXType, date, nTimes, colorAndPos, posStr, images, layerName, dlData);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("产品生成失败");
            return null;
        }
    }

}
